<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('申请人')" @change="echoInfo" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请部门')" prop="deptId">
            <tree-select
              v-model="form.deptId"
              :default-expand-all="true"
              :data="initData.deptOptions"
              :placeholder="$t('请选择')"
              node-key="id"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('拟离职日期')" prop="lastTime">
            <el-date-picker
              v-model="form.lastTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('拟离职日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('交接人')" prop="handoverUser">
            <UserSelect v-model="form.handoverUser" :placeholder="$t('交接人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('交接时间')" prop="times">
            <el-date-picker
              v-model="form.times"
              type="daterange"
              range-separator="至"
              :start-placeholder="$t('交接开始时间')"
              :end-placeholder="$t('交接结束时间')"
            />
          </el-form-item>
        </el-col>

        <el-col v-if="form.actStatus === 'W'" :span="12">
          <el-form-item :label="$t('实际离职时间')" prop="actualResignationTime">
            <span slot="label">
              {{ $t('实际离职时间') }}
              <el-tooltip :content="$t('维护实际离职时间之后，申请人账号将被禁用')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-date-picker
              v-model="form.actualResignationTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('实际离职时间')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="$t('离职原因')" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :placeholder="$t('离职原因')"
              show-word-limit
              maxlength="1000"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!--文件-->
      <FileTable :list.sync="form.fileList" :data-type="dataType" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="hr:quit" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
import { saveHrQuit, getHrQuit } from '@/api/oa/hr/hrQuit'
import { treeselect } from '@/api/system/dept'
import { listPost } from '@/api/system/post'
import TreeSelect from '@/components/TreeSelect'
import { getUser } from '@/api/system/user'

export default {
  components: { TreeSelect },
  data() {
    return {
      // 菜单标识
      menuKey: this.$t('hr_quit'),
      otherBtnHide: false,
      dataType: 'hr_quit',

      // 表单参数
      form: {
        times: [],
        fileList: []
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], lastTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], handoverUser: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], applyTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], times: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], remark: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      initData: {
        deptOptions: [],
        hrPositions: []
      },
      userName: ''
    }
  },
  created() {
    this.$bus.$emit('async_done')
    this.initDataMethod()
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getHrQuit(data.id).then(response => {
          this.form = response.data
          this.form.times = [this.form.handoverDateStart, this.form.handoverDateEnd]
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actTitle: undefined,
        userId: undefined,
        deptId: undefined,
        postId: undefined,
        entryTime: undefined,
        lastTime: undefined,
        remark: undefined,
        reasonForLeaving: undefined,
        applyTime: undefined,
        handoverDateStart: undefined,
        handoverDateEnd: undefined,
        handoverUser: undefined,
        actualResignationTime: undefined
      }
      this.initReset()
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.form.actTitle = this.$t('离职申请')
            this.userName = undefined
            this.loading = true
            this.form.handoverDateStart = this.form.times[0]
            this.form.handoverDateEnd = this.form.times[1]
            // 保存数据
            saveHrQuit(this.form).then(response => {
              if (response.code === 200) {
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  // 启动流程
                  this.startProcess(response.data)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = dataId.actTitle
      // 业务表名
      processData.dataTable = 'hr_quit'
      // 业务ID
      processData.dataId = dataId.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/hr/quit/hrQuitForm'
      processData.viewPath = '@/views/oa/hr/quit/hrQuitView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    initDataMethod() {
      treeselect().then(response => {
        this.initData.deptOptions = response.data
      })
      // 职位
      listPost({}).then(response => {
        this.initData.hrPositions = response.rows
      })
    },
    echoInfo() {
      if (this.otherBtnHide) {
        return
      }
      if (this.form.userId !== null && this.form.userId !== undefined && this.form.userId !== '') {
        getUser(this.form.userId).then(res => {
          this.form.deptId = res.data.deptId
          this.userName = res.data.nickName
        })
      }
    },
    // 初始化重置表单 数据
    initReset() {
      // 获取当前时间
      const now = new Date()
      const year = now.getFullYear() // 得到年份
      let month = now.getMonth() // 得到月份
      let date = now.getDate() // 得到日期
      month = month + 1
      month = month.toString().padStart(2, '0')
      date = date.toString().padStart(2, '0')
      this.form.applyTime = `${year}-${month}-${date}`
      const next = new Date()
      next.setMonth(next.getMonth() + 1)
      const year1 = next.getFullYear() // 得到年份
      let month1 = next.getMonth() // 得到月份
      let date1 = next.getDate() // 得到日期
      month1 = month1 + 1
      month1 = month1.toString().padStart(2, '0')
      date1 = date1.toString().padStart(2, '0')
      this.form.lastTime = `${year1}-${month1}-${date1}`
    }

  }

}
</script>
